package com.netmi.myuploadfileretrofit.utils;

/**
 * 类描述：
 * 创建人：tgw
 * 创建时间：2020/7/11
 * 修改备注：
 */

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

/**
 * Created by kimhuang on 2018/5/6.
 */

public class PermissionUtil {
    private static final String LOGTAG = PermissionUtil.class.getSimpleName();

    public static final int REQUEST_CODE_PERMISSION = 0x12;
    public static final int FLOAT_REQUEST_CODE = 100;
    public static boolean FLOAT_IS_START = false;

    static boolean is = true;
    static boolean isFinishGrantPermission = false;
    public static final int PERMISSION_TYPE_NULL = -1;
    public static final int PERMISSION_TYPE_ALL = 0;
    public static final int PERMISSION_TYPE_IMPORTANT = 1;
    public static final int PERMISSION_TYPE_CAMERA = 2;
    public static final int PERMISSION_TYPE_VOICE = 3;
    public static final int PERMISSION_TYPE_MAP = 4;
    public static final int PERMISSION_TYPE_SMS = 5;
    public static final int PERMISSION_TYPE_MEDIA = 6;
    public static final int PERMISSION_TYPE_BLUETOOTH = 7;

    public static final int PERMISSION_TYPE_INIT_APP = 8; //允许应用安装未知app

    public static final int PERMISSION_TYPE_READ_CONTACTS = 9; //读取通讯录


    public static String[] IMPORTANT_PERMISSIONS = {
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
    };

    public static String[] CAMERA_PERMISSIONS = {
            Manifest.permission.CAMERA,
    };

    public static String[] VOICE_PERMISSIONS = {
            Manifest.permission.RECORD_AUDIO,
    };

    public static String[] SMS_PERMISSIONS = {
            Manifest.permission.CALL_PHONE,
            Manifest.permission.SEND_SMS,
    };

    public static String[] MAP_PERMISSIONS = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
    };

    public static String[] ALL_PERMISSIONS = {
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.SYSTEM_ALERT_WINDOW,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CALL_PHONE,
//            Manifest.permission.SEND_SMS,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
    };

    public static String[] MEDIA_PERMISSIONS = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
    };

    public static String[] BLUETOOTH_PERMISSIONS = {
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.ACCESS_COARSE_LOCATION,
    };

    public static String[] NIT_APP_PERMISSIONS = {
            Manifest.permission.REQUEST_INSTALL_PACKAGES
    };

    public static String[] READ_CONTACTS_PERMISSIONS = {
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.WRITE_CONTACTS
    };


    public static boolean requirePermissions(final Context context, final int type) {
        String[] pList = null;
        isFinishGrantPermission = false;
        String dialogMessage = "";
        if (type == PERMISSION_TYPE_IMPORTANT) {
            pList = IMPORTANT_PERMISSIONS;
            dialogMessage = "需要存储及电话权限才能启动应用";
        } else if (type == PERMISSION_TYPE_CAMERA) {
            pList = CAMERA_PERMISSIONS;
            dialogMessage = "需要该权限才能使用相机";
        } else if (type == PERMISSION_TYPE_VOICE) {
            pList = VOICE_PERMISSIONS;
            dialogMessage = "需要麦克风权限才能使用录音";
        } else if (type == PERMISSION_TYPE_MAP) {
            pList = MAP_PERMISSIONS;
            dialogMessage = "需要该权限才能打开地图";
        } else if (type == PERMISSION_TYPE_SMS) {
            pList = SMS_PERMISSIONS;
            dialogMessage = "需要该权限才能发送短信";
        } else if (type == PERMISSION_TYPE_ALL) {
            pList = ALL_PERMISSIONS;
            dialogMessage = "为了能够更好地使用应用，请允许授权";
        } else if (type == PERMISSION_TYPE_MEDIA) {
            pList = MEDIA_PERMISSIONS;
            dialogMessage = "需要相机，麦克风，存储该权限才能录制音视频";
        } else if (type == PERMISSION_TYPE_BLUETOOTH) {
            pList = BLUETOOTH_PERMISSIONS;
            dialogMessage = "需要该权限才能使用蓝牙";
        } else if (type == PERMISSION_TYPE_INIT_APP) {
            pList = NIT_APP_PERMISSIONS;
            dialogMessage = "安装app需要您勾选允许安装未知应用权限";
        } else if (type == PERMISSION_TYPE_READ_CONTACTS) {
            pList = READ_CONTACTS_PERMISSIONS;
            dialogMessage = "使用该功能需要读取通讯录信息权限";
        } else {
            pList = IMPORTANT_PERMISSIONS;
        }

        List<String> needGrantPermissions = new ArrayList<>();
        boolean is = true;
        for (String p : pList) {
            if (TextUtils.isEmpty(p)) {
                continue;
            } else if (ContextCompat.checkSelfPermission(context, p) != PackageManager.PERMISSION_GRANTED) {
                Log.d(LOGTAG, "need granted permission " + p);
                if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, p)) {
                    new AlertDialog.Builder(context)
                            .setCancelable(false)
                            .setMessage(dialogMessage)
                            .setPositiveButton("去授权", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    startAppPermissionSetting(context);
                                    dialog.dismiss();
                                }
                            })
                            .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (type == PERMISSION_TYPE_IMPORTANT) {
                                        ((Activity) context).finish();
                                    }
                                    dialog.dismiss();
                                }
                            })
                            .create()
                            .show();
                } else {
                    needGrantPermissions.add(p);
                }

                is = false;
                break;
            }
        }

        if (needGrantPermissions != null && needGrantPermissions.size() > 0) {
            try {
                ActivityCompat.requestPermissions((Activity) context, needGrantPermissions.toArray(
                        new String[needGrantPermissions.size()]), REQUEST_CODE_PERMISSION);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return is;
    }


    public static boolean requireRxPermissions(final Activity activity, String[] permissionGroups) {

        RxPermissions rxPermissions = new RxPermissions(activity);
        boolean is = true;
        for (String s : permissionGroups) {
            if (!rxPermissions.isGranted(s)) {
                is = false;
                break;
            }
        }
        return is;
    }

    public static void showRequestPermissionDialog(final Activity activity, final int type) {
        String[] pList = null;
        String dialogMessage = "";
        if (type == PERMISSION_TYPE_IMPORTANT) {
            pList = IMPORTANT_PERMISSIONS;
            dialogMessage = "需要存储及电话权限才能启动应用";
        } else if (type == PERMISSION_TYPE_CAMERA) {
            pList = CAMERA_PERMISSIONS;
            dialogMessage = "需要相机权限才能使用相机";
        } else if (type == PERMISSION_TYPE_VOICE) {
            pList = VOICE_PERMISSIONS;
            dialogMessage = "需要麦克风权限才能使用录音";
        } else if (type == PERMISSION_TYPE_MAP) {
            pList = MAP_PERMISSIONS;
            dialogMessage = "需要定位权限才能打开地图";
        } else if (type == PERMISSION_TYPE_SMS) {
            pList = SMS_PERMISSIONS;
            dialogMessage = "需要该权限才能发送短信";
        } else if (type == PERMISSION_TYPE_ALL) {
            pList = ALL_PERMISSIONS;
            dialogMessage = "为了能够更好地使用应用，请允许授权";
        } else if (type == PERMISSION_TYPE_MEDIA) {
            pList = MEDIA_PERMISSIONS;
            dialogMessage = "需要相机，麦克风，存储该权限才能录制音视频";
        } else if (type == PERMISSION_TYPE_INIT_APP) {
            pList = NIT_APP_PERMISSIONS;
            dialogMessage = "安装app需要您勾选允许安装未知应用权限";
        } else if (type == PERMISSION_TYPE_READ_CONTACTS) {
            pList = READ_CONTACTS_PERMISSIONS;
            dialogMessage = "使用该功能需要读取通讯录信息权限";
        } else {
            pList = IMPORTANT_PERMISSIONS;
        }


//        DebugLog.showIOSAlert(activity, "提醒", dialogMessage, "放弃", "去授权", new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        if (type == PERMISSION_TYPE_IMPORTANT) {
//                            activity.finish();
//                        }
//
//                    }
//                },
//                new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        startAppPermissionSetting(activity);
//                    }
//                });

        new AlertDialog.Builder(activity)
                .setCancelable(false)
                .setMessage(dialogMessage)
                .setPositiveButton("去授权", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppPermissionSetting(activity);
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (type == PERMISSION_TYPE_IMPORTANT) {
                            activity.finish();
                        }
                        dialog.dismiss();
                    }
                })
                .create()
                .show();


    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static void requirePermissions(final Activity activity, final int type,
                                          @NonNull final RequirePermissionDialogListener dialogListener) {
        if (activity == null || activity.isDestroyed() || activity.isFinishing()) return;
        String[] permissionGroups = null;
        isFinishGrantPermission = false;
        String dialogMessage = "";
        if (type == PERMISSION_TYPE_IMPORTANT) {
            permissionGroups = IMPORTANT_PERMISSIONS;
            dialogMessage = "需要存储及电话权限才能启动应用";
        } else if (type == PERMISSION_TYPE_CAMERA) {
            permissionGroups = CAMERA_PERMISSIONS;
            dialogMessage = "需要该权限才能使用相机";
        } else if (type == PERMISSION_TYPE_VOICE) {
            permissionGroups = VOICE_PERMISSIONS;
            dialogMessage = "需要麦克风权限才能使用录音";
        } else if (type == PERMISSION_TYPE_MAP) {
            permissionGroups = MAP_PERMISSIONS;
            dialogMessage = "需要该权限才能打开地图";
        } else if (type == PERMISSION_TYPE_SMS) {
            permissionGroups = SMS_PERMISSIONS;
            dialogMessage = "需要该权限才能发送短信";
        } else if (type == PERMISSION_TYPE_ALL) {
            permissionGroups = ALL_PERMISSIONS;
            dialogMessage = "为了能够更好地使用应用，请允许授权";
        } else if (type == PERMISSION_TYPE_MEDIA) {
            permissionGroups = MEDIA_PERMISSIONS;
            dialogMessage = "需要相机，麦克风，存储该权限才能录制音视频";
        } else if (type == PERMISSION_TYPE_INIT_APP) {
            permissionGroups = NIT_APP_PERMISSIONS;
            dialogMessage = "安装app需要您勾选允许安装未知应用权限";
        } else if (type == PERMISSION_TYPE_READ_CONTACTS) {
            permissionGroups = READ_CONTACTS_PERMISSIONS;
            dialogMessage = "使用该功能需要读取通讯录信息权限";
        } else {
            permissionGroups = IMPORTANT_PERMISSIONS;
        }
        final String tips = dialogMessage;
        final RxPermissions rxPermissions = new RxPermissions(activity);
        final String[] finalPermissionGroups = permissionGroups;
        final boolean[] firstRe = {true};
        Observable.timer(10, TimeUnit.MILLISECONDS)
                .compose(rxPermissions.ensureEach(permissionGroups))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            // 用户已经同意该权限
                            //判断应有权限是否全部同意
                            if (PermissionUtil.requireRxPermissions(activity, finalPermissionGroups)) {
                                if (!isFinishGrantPermission) {
                                    isFinishGrantPermission = true;
                                    dialogListener.onSuccess();
                                }
                            }
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            if (!isFinishGrantPermission) {
                                isFinishGrantPermission = true;
                                dialogListener.onFailure(tips);
                            }
                        } else {
                            if (PermissionUtil.requireRxPermissions(activity, finalPermissionGroups)) {
                                if (!isFinishGrantPermission) {
                                    isFinishGrantPermission = true;
                                    dialogListener.onSuccess();
                                }
                            } else {
                                if (firstRe[0]) {
                                    PermissionUtil.showRequestPermissionDialog(activity, type);
                                    firstRe[0] = false;
                                }
                            }
                        }
                    }
                });
    }

    public static void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                                  @NonNull int[] grantResults, RequirePermissionListener listener) {
        if (requestCode == REQUEST_CODE_PERMISSION) {
            List<String> grantedPermissions = new ArrayList<>();
            List<String> deniedPermissions = new ArrayList<>();
            if (grantResults.length > 0) { //安全写法，如果小于0，肯定会出错了
                for (int i = 0; i < grantResults.length; i++) {
                    int grantResult = grantResults[i];
                    String permission = permissions[i];
                    if (grantResult == PackageManager.PERMISSION_DENIED) {
                        deniedPermissions.add(permission);
                    } else {
                        grantedPermissions.add(permission);
                    }
                }
            }
            if (deniedPermissions.size() > 0) {
                listener.onDenied(deniedPermissions);
            }

            if (grantedPermissions.size() > 0) {
                listener.onGranted(grantedPermissions);
            }
            if (deniedPermissions == null || deniedPermissions.size() == 0) {
                listener.onGranted();
            }
        }
    }

    /**
     * 应用信息页面
     *
     * @param context
     */
    public static void startAppDetailSetting(final Context context) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
        }
        context.startActivity(intent);
    }

    /**
     * 在Android6.0以上我们需要去打开授权应用,使用悬浮窗
     *
     * @param activity
     */
    public static void startFloatPermissions(Activity activity, int requestCode) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(activity.getApplicationContext())) {
                //启动Activity让用户授权
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                intent.setData(Uri.parse("package:" + activity.getPackageName()));
                activity.startActivityForResult(intent, requestCode);
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private boolean isHasInstallPermissionWithO(Activity context) {
        if (context == null) {
            return false;
        }
        return context.getPackageManager().canRequestPackageInstalls();
    }

    /**
     * 在Android8.0以上我们需要去打开授权应用,使用自动安装权限
     *
     * @param activity
     */
    public static void startInitAppPermissions(Activity activity, int requestCode) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (activity == null) {
                return;
            }
            Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
            ((Activity) activity).startActivityForResult(intent, requestCode);
        }
    }


    /**
     * 应用权限设置页面
     *
     * @param context
     */
    public static void startAppPermissionSetting(final Context context) {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", context.getPackageName(), null);
        intent.setData(uri);
        context.startActivity(intent);
    }

    public interface RequirePermissionListener {
        //授权成功
        void onGranted();

        //授权部分
        void onGranted(List<String> grantedPermissions);

        //拒绝授权
        void onDenied(List<String> deniedPermissions);
    }

    public interface RequirePermissionDialogListener {
        // 授权成功
        void onSuccess();

        // 授权失败
        void onFailure(String tips);
    }


    public static boolean checkPermissions(final Activity context, int type) {

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {

            if (type == PERMISSION_TYPE_IMPORTANT) {
                if ((ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) ||
                        ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
//                    ActivityCompat.requestPermissions(context, IMPORTANT_PERMISSIONS, REQUEST_CODE_PERMISSION);
                    requirePermissions(context, type);
                } else {
                    return false;//原先已有该权限存储及电话
                }
            } else if (type == PERMISSION_TYPE_VOICE) {
                if (ActivityCompat.checkSelfPermission(context, VOICE_PERMISSIONS[0]) != PackageManager.PERMISSION_GRANTED) {
//                    ActivityCompat.requestPermissions(context, VOICE_PERMISSIONS, REQUEST_CODE_PERMISSION);
                    requirePermissions(context, type);
                } else {
                    return false;//原先已有该权限录音
                }
            }


        }
        return true;
    }


}

